package com.xiaoyy.sso.gateway.listener;

import com.xiaoyy.core.common.cache.CacheConst;
import com.xiaoyy.sso.core.integration.LoginLogIntegration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/***
 * 该监听生效需要在redis配置文件中把notify-keyspace-events Ex 这一行的注释打开
 * 只监听过期的key
 * */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private LoginLogIntegration loginLogIntegration;
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String expiredKey = message.toString();
        logger.info("过期的redis缓存Key："+expiredKey);
        // token 失效按退出登入处理
        if (expiredKey.startsWith(CacheConst.ACCESS_TOKEN)){
            String [] keys=expiredKey.split(":");
            if (keys.length>1) {
                String accessToken=keys[1];
                loginLogIntegration.saveLogout(accessToken);
            }
        }

    }
}